package com.diyunapp.xilinapp.me;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.JifenBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.AbDateUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
//我的积分
public class integralActivity extends StatusBarFragmentActivity {

    @Bind(R.id.recharge_record_tv)
    TextView rechargeRecordTv;
    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.account_money)
    TextView accountMoney;
    @Bind(R.id.integral_fresh_lv)
    ListView integralFreshLv;
    @Bind(R.id.integral_refresh_view)
    SwipeRefreshLayout integralRefreshView;
    private View headView;
private String jiFenNum;


private List<JifenBean.DateBean> info = new ArrayList<>();
    private LayoutInflater inflater;
    private IntegralAdapter integralAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        integralAdapter=new IntegralAdapter(this);
        ButterKnife.bind(this);
        headView = findViewById(R.id.jifen_menubar_inc);
        super.MenuWidget(headView);
        jiFenNum=getIntent().getExtras().getString("member_points");
        accountMoney.setText(jiFenNum);
        getData();
        integralFreshLv.setAdapter(integralAdapter);
        integralRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        integralRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                getData();
            }
        });
    }
    private void getData() {
        String url = ""+ MainActivity.url+"act=goods&op=my_integral&username="+MainActivity.myLogin.getUsername()+"";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        integralRefreshView.setRefreshing(false);
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        toast(resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
                            if (result == 200) {
                                info.clear();
                                JSONArray listArray = resultObject.getJSONArray("date");
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.getJSONObject(i);
                                    long pl_addtime = recordObject.optLong("pl_addtime");
                                    String pl_desc = recordObject.optString("pl_desc");
                                    String pl_points = recordObject.getString("pl_points");
                                    info.add(new JifenBean.DateBean(pl_addtime, pl_desc, pl_points));
                                    Log.i("zhangxiaoxidebug", "resultinfo=" + info);
                                }
                                integralAdapter.setList(info);
                                integralAdapter.notifyDataSetChanged();

                            } else {
                                toast("当前暂无数据");
                                integralRefreshView.setVisibility(View.GONE);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            integralRefreshView.setRefreshing(false);
                            toast("查询失败");
                            e.printStackTrace();
                            integralRefreshView.setVisibility(View.GONE);
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
//                        bidFreshLv.onRefreshComplete();
                        toast("请求失败");
                        integralRefreshView.setVisibility(View.GONE);

                    }
                });
    }
    @OnClick({R.id.recharge_record_tv,R.id.go_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.recharge_record_tv:
//    dialog

            getJIfenRxule();
                break;
            case R.id.go_back:
                finish();
                break;


        }
    }

    private void getJIfenRxule() {
        String url = ""+MainActivity.url+"act=goods&op=aaa";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        toast(resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
                            if (result == 200) {
                                JSONObject recordObject = resultObject.optJSONObject("datas");

                                    String zhuce = recordObject.optString("zhuce");
                                    String denglu = recordObject.optString("denglu");
                                    String wancheng = recordObject.getString("wancheng");
                                    String zongjia=recordObject.optString("zongjia");
                                    String xiane=recordObject.optString("xiane");
//                                    String information="1.成功注册会员：增加20积分；会员每天登录：增加30积分；评价完成订单增加50积分" +
//                                            "2.购物并付款成功后将获得订单总价5%（最高限额不超过800积分）。" +
//                                            "3.如订单发生退款，退货等问题时，积分将不予退还";
                                String information="1.成功注册会员：增加"+zhuce+"积分；会员每天登录：增加"+denglu+"积分；评价完成订单增加"+wancheng+"积分\n" +
                                        "2.购物并付款成功后将获得订单总价"+zongjia+"%（最高限额不超过"+xiane+"积分）。\n" +
                                        "3.如订单发生退款，退货等问题时，积分将不予退还\n";
                                initBandDlg(information);
                            } else {
                                initBandDlg("1.成功注册会员：增加20积分；会员每天登录：增加30积分；评价完成订单增加50积分\n" +
                                            "2.购物并付款成功后将获得订单总价5%（最高限额不超过800积分\n）。" +
                                            "3.如订单发生退款，退货等问题时，积分将不予退还\n");
                                toast("当前暂无数据");
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            initBandDlg("1.成功注册会员：增加20积分；会员每天登录：增加30积分；评价完成订单增加50积分\n" +
                                    "2.购物并付款成功后将获得订单总价5%（最高限额不超过800积分）。\n" +
                                    "3.如订单发生退款，退货等问题时，积分将不予退还\n");
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
//                        bidFreshLv.onRefreshComplete();
                        toast("请求失败");


                    }
                });
    }


    class IntegralAdapter extends BaseAdapter {
        private List<JifenBean.DateBean> info = new ArrayList<JifenBean.DateBean>();
        private Context context;
        public IntegralAdapter( Context myContext) {
            super();
            this.context = myContext;

        }
        public void setList(List<JifenBean.DateBean> list) {
            this.info = list;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
            private  ViewHolder viewHolder;
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_integral_record, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            JifenBean.DateBean data_info = info.get(position);
            viewHolder.tradeTime.setText(AbDateUtil.getStringByFormat(data_info.getPl_addtime()*1000,"yyyy-MM-dd hh:mm:ss"));
            viewHolder.tradeWay.setText(data_info.getPl_desc());
            viewHolder.tradeMoney.setText(data_info.getPl_points());
            return convertView;
        }

         class ViewHolder {
            @Bind(R.id.trade_way)
            TextView tradeWay;
            @Bind(R.id.trade_time)
            TextView tradeTime;
            @Bind(R.id.trade_money)
            TextView tradeMoney;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    /**
     * @param m 提现金额
     * */
    public void initBandDlg(final String m){
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        final View getmoney = inflater.inflate(R.layout.dlg_jifenrlue, null);
        TextView yes = ButterKnife.findById(getmoney,R.id.yes);
        TextView information = ButterKnife.findById(getmoney,R.id.information);
        information.setText(m);

        // 1. Instantiate an AlertDialog.Builder with its constructor
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 2. Chain together various setter methods to set the dialog characteristics
        builder.setView(getmoney);
        // 3. Get the AlertDialog from create()
        final AlertDialog dialog = builder.create();
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

